package com.forward;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class PdfReader {
    public static void main(String[] args) {
        File file = new File("C:\\Users\\WLAR\\Desktop\\a.pdf");

        List<String> strings = getbase64Photos(file, 1, 2);
        System.out.println(strings);

    }


    /**
     * 提取指定PDF页面的图片转换为Base64的List
     * 注意：图片提取的顺序是PDF创建时图片插入的顺序
     *
     * @param file       pdf文件
     * @param startIndex
     * @param endIndex
     * @throws Exception
     */
    public static List<String> getbase64Photos(File file, int startIndex, int endIndex) {
        List<String> photos = new ArrayList<>();
        try (PDDocument document = PDDocument.load(file)) {
            //TODO 下标从0开始，所以-1
            for (int i = startIndex - 1; i < endIndex; i++) {
                PDPage pdfpage = document.getPage(i);
                // get resource of pdf
                PDResources pdResources = pdfpage.getResources();
                Iterable<COSName> xObjectNames = pdResources.getXObjectNames();
                Iterator<COSName> iterator = xObjectNames.iterator();
                while (iterator.hasNext()) {
                    PDXObject o = pdResources.getXObject(iterator.next());
                    if (o instanceof PDImageXObject) {
                        //得到BufferedImage对象
                        BufferedImage image = ((PDImageXObject) o).getImage();
//                        String base64img = Base64Util.convertimgtoBase64(image);
                        // 可以打印到本地，查看输出顺序
                        String imglocation = "C:\\Users\\WLAR\\Desktop\\";
                        File imgfile = new File(imglocation + UUID.randomUUID().toString() + ".png");
                        ImageIO.write(image, "png", imgfile);

//                        photos.add("data:image/jpg;base64," + base64img);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return photos;
    }


}    